package com.cloud.point.jvm;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StopWatch;

/**
 * 直接内存的使用
 *
 * @author 24373
 * @version 1.0
 * @date 2024-06-09 12:09
 */
@Slf4j
public class TestDirectMemory {
    private static final int _1MB = 1024 * 1024;
    private static final String FROM = "C:\\CentOs\\CentOS-7-x86_64-DVD-1810.iso";
    private static final String TO = "C:\\CentOs\\CentOS-2.iso";

    public static void main(String[] args) {
        //testIO();
        testDirectMemory();
    }

    /**
     * 直接内存的使用
     */
    private static void testDirectMemory() {
        StopWatch watch = new StopWatch();
        watch.start();
        try (
                FileChannel from = new FileInputStream(FROM).getChannel();
                FileChannel to = new FileOutputStream(TO).getChannel();
        ) {
            ByteBuffer byteBuffer = ByteBuffer.allocateDirect(_1MB);
            while (true) {
                int len = from.read(byteBuffer);
                if (len == -1) {
                    break;
                }
                byteBuffer.flip();
                to.write(byteBuffer);
                byteBuffer.clear();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        watch.stop();
        log.info("DirectMemory: {}", watch.getTotalTimeSeconds());
    }

    /**
     * 普通io的使用
     */
    public static void testIO() {
        StopWatch watch = new StopWatch();
        watch.start();
        try (
                FileInputStream from = new FileInputStream(FROM);
                FileOutputStream to = new FileOutputStream(TO);
        ) {
            byte[] buffer = new byte[_1MB];
            while (true) {
                int len = from.read(buffer);
                if (len == -1) {
                    break;
                }
                to.write(buffer, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        watch.stop();
        log.info("IO: {}", watch.getTotalTimeSeconds());
    }

}
